package com.cogwheel.framework.graphics;

import java.awt.Color;

import javax.media.opengl.GL2;

import com.cogwheel.framework.init.CPreferences;
import com.cogwheel.framework.util.CParticle;
import com.cogwheel.framework.util.CPoint;
import com.cogwheel.framework.util.CRectangle;
import com.cogwheel.framework.util.CUtils;

public class CParticlesTextured extends CParticles {

	public int WIDTH, HEIGHT = 10;
	
	public CParticlesTextured(CPreferences preferences, String texture, CPoint position, int number) {
		super(preferences, position, number);
		this.TextureID = texture;
	}
	
	@Override
	public void CUpdate(){
		for (int c = 0; c < particles.size(); c++){
			CParticle part = particles.get(c);
			if (part.Active){
				part.LifeTime -= part.Decay;
				part.Position.x += part.Speed.x;
				part.Position.y += part.Speed.y;
				part.Speed.y += 0.0005;
			} else {
				part.Active = true; continue;
			}
			
			if (part.LifeTime <= 0){ CCreateParticle(c); continue; } else{
				particles.set(c, part);	
			}
		}
	}
	
	@Override
	public void CCreateParticle(int i){
		CParticle part = new CParticle();
		part.LifeTime = (float)CUtils.Randomiser.nextInt(360);
		part.Decay = CUtils.Randomiser.nextInt(2) + 1;
		part.Color = new Color(CUtils.Randomiser.nextInt(155) + 100, CUtils.Randomiser.nextInt(50) + 200, 0);
		part.Position = new CPoint(Position.x, Position.y);
		part.Speed = new CPoint(2.5f - CUtils.Randomiser.nextInt(5) + CUtils.Randomiser.nextFloat() * 2, CUtils.Randomiser.nextInt(5) + 3 + CUtils.Randomiser.nextFloat() * 2);
		part.Active = false;
		
		particles.set(i, part);
	}
	
	@Override
	public void CDraw(GL2 gl){
		for (int c = 0; c < particles.size(); c++){
			if (particles.get(c).Active){
				Dimensions = new CRectangle(particles.get(c).Position, WIDTH, HEIGHT);
				Color = particles.get(c).Color;
				gl.glLoadIdentity();
				CToOrtho();
				CBindTexture(gl);
				CDraw2D(gl);
			}
		}
	}
	@Override
	public void CDraw2D(GL2 gl){
		gl.glTranslatef(xa, ya, 1f);
		gl.glColor4f((float)Color.getRed()/255, (float)Color.getGreen()/255, (float)Color.getBlue()/255, (float)Color.getAlpha()/255);
		gl.glBegin(GL2.GL_QUADS);
			gl.glTexCoord2f(0.0f, 1.0f); gl.glVertex2f(-w, h);
			gl.glTexCoord2f(1.0f, 1.0f); gl.glVertex2f(w, h);
			gl.glTexCoord2f(1.0f, 0.0f); gl.glVertex2f(w, -h);
			gl.glTexCoord2f(0.0f, 0.0f); gl.glVertex2f(-w, -h);
		gl.glEnd();
		gl.glColor3f(1f, 1f, 1f);
	}
	
}
